  layui.config({
        base: './../../layui/lay/modules/'
    });
	

  var resizeWorldMapContainer = function (worldMapContainer) {
		  console.log(window.innerWidth)
		  if ( window.innerWidth <= 500){
			  worldMapContainer.style.width=window.innerWidth+'px';
		  }else{
			  worldMapContainer.style.width=(window.innerWidth/2)-20+'px';

		  }
		};
		
		
var booktable=new Vue({
		el: '#booktable',
		data:{
			book:null,
			id:null,
			bookName:null,
			charptTitle:null,
			bookauthor:null,
			content:null,
			//章节id
			cid:null,
			cnum:0,
			layer:null,
			notice:null,
			//章节数
			chapterNum:0
		},
		methods:{
			saveChapter:function(id){
				var data={
					"id":id,
					"content":this.content
					}
			
				var formData = new FormData();
				formData.append('id', id);
				formData.append('content', this.content);
				formData.append('title', this.charptTitle);
				this.$http.post(global_url+'/admin/chapter/update/',formData)
					.then(
					response=>{
						this.notice.init({
							type: "default",
							autoClose: true,
							title: "处理成功",
							desktop: true,
						});
						charinit()

					},					
					response=>{
						this.notice.init({
							type: "danger",
							autoClose: true,
							title: "请求失败",
							desktop: true,
						});
					})
				},
			deleteChapter:function(id){
				this.$http.post(global_url+'/admin/chapter/delete/'+id)
					.then(
					response=>{
						this.notice.init({
							type: "default",
							autoClose: true,
							title: "处理成功",
							desktop: true,
						});
						setTimeout(function(){	location.reload();},800)
						charinit()
					},					
					response=>{
						this.notice.init({
							type: "danger",
							autoClose: true,
							title: "请求失败",
							desktop: true,
						});
					})
			},
			onlineUpdataChapter:function(){
				this.$http.post(global_url+'/admin/chapter/online/update/'+this.book.id)
					.then(
					response=>{
						this.notice.init({
							type: "default",
							autoClose: true,
							title: "提交成功",
							desktop: true,
						});
						charinit()
					},					
					response=>{
						this.notice.init({
							type: "danger",
							autoClose: true,
							title: "请求失败",
							desktop: true,
						})
					})

			},
			addChapter:function(){
				var data={
					"novelId":this.book.id,
					"chapterName":this.charptTitle,
					"chapterContent":this.content
				}
				this.$http.post(global_url+'/admin/chapter/add/',data)
					.then(
					response=>{
						this.layer.msg(response.body.msg)
						this.notice.init({
							type: "default",
							autoClose: true,
							title: "处理成功",
							desktop: true,
						});
						charinit()
					},					
					response=>{
						this.notice.init({
							type: "danger",
							autoClose: true,
							title: "请求失败",
							desktop: true,
						});
					})
				
			},
			addOnlineChapter:function(url){
				var formData = new FormData();
				formData.append('url', url);
				formData.append('nid', this.book.id);
				formData.append('cno', this.chapterNum+1);
				this.$http.post(global_url+'/admin/chapter/online/add/',formData)
					.then(
					response=>{
						this.notice.init({
							type: "default",
							autoClose: true,
							title: "处理成功",
							desktop: true,
						});
						charinit()
					},					
					response=>{
						this.notice.init({
							type: "danger",
							autoClose: true,
							title: "请求失败",
							desktop: true,
						});
					})
			}
		}
	});

	
 function charinit(){
	 // 绘制图表。
	 var option={
	 	xAxis: {
	 		type: 'category',
	 		data: ['章节数', '收藏数', '人气'],
	 	
	 	},
	 	yAxis: {
	 		type: 'value',
	 	},
	 	series: [{
	 		data: [booktable.chapterNum, booktable.book.collectionNumber, booktable.book.sentiment],
	 		type: 'bar',
	 		label: {
	 			normal: {
	 				show: true,
	 				position: 'top'
	 			}
	 		},
	 		itemStyle: {
	 				normal: {
	 					// 定制显示（按顺序）
	 					color: function(params) { 
	 						var colorList = ['#C33531','#0AAF9F','#64BD3D']; 
	 						return colorList[params.dataIndex] 
	 					}
	 				},
	 		}
	 		
	 	}],
	 	tooltip : {
	 		trigger: 'axis',
	 		formatter:function(params){
	 			return  params[0].value
	 		}
	 	}
	 }  
	 echarts.init(document.getElementById('chart')).setOption(option);
	 
 }

layui.use(['element','flow','form','layer','layedit','laydate','upload','notice'],function(){
	var flow = layui.flow;
	
	

    var form = layui.form
        layer = parent.layer === undefined ? layui.layer : top.layer,
        laypage = layui.laypage,
        upload = layui.upload,
        layedit = layui.layedit,
        laydate = layui.laydate,
        $ = layui.jquery;

    //用于同步编辑器内容到textarea
    layedit.sync(editIndex);
	
	//初始化vue
	booktable.layer=layer
	booktable.notice=layui.notice

    //上传缩略图
    upload.render({
        elem: '.thumbBox',
        url: '../../json/userface.json',
        method : "get",  //此处是为了演示之用，实际使用中请将此删除，默认用post方式提交
        done: function(res, index, upload){
            var num = parseInt(4*Math.random());  //生成0-4的随机数，随机显示一个头像信息
            $('.thumbImg').attr('src',res.data[num].src);
            $('.thumbBox').css("background","#fff");
        }
    });

    //格式化时间
    function filterTime(val){
        if(val < 10){
            return "0" + val;
        }else{
            return val;
        }
    }
    //定时发布
    var time = new Date();
    var submitTime = time.getFullYear()+'-'+filterTime(time.getMonth()+1)+'-'+filterTime(time.getDate())+' '+filterTime(time.getHours())+':'+filterTime(time.getMinutes())+':'+filterTime(time.getSeconds());
    laydate.render({
        elem: '#release',
        type: 'datetime',
        trigger : "click",
        done : function(value, date, endDate){
            submitTime = value;
        }
    });
    form.on("radio(release)",function(data){
        if(data.elem.title == "定时发布"){
            $(".releaseDate").removeClass("layui-hide");
            $(".releaseDate #release").attr("lay-verify","required");
        }else{
            $(".releaseDate").addClass("layui-hide");
            $(".releaseDate #release").removeAttr("lay-verify");
            submitTime = time.getFullYear()+'-'+(time.getMonth()+1)+'-'+time.getDate()+' '+time.getHours()+':'+time.getMinutes()+':'+time.getSeconds();
        }
    });

    form.verify({
        newsName : function(val){
            if(val == ''){
                return "文章标题不能为空";
            }
        },
        content : function(val){
            if(val == ''){
                return "文章内容不能为空";
            }
        }
    })
    form.on("submit(save_book)",function(data){
       var types=new Array(data.field.length);
       var i = 0;
       for(var key in data.field){
       	var pdata={
       		"categoryName":key,
       	}
       	types[i]=pdata;
       	i++;
       }
	   var data={
	   	"id":booktable.book.id,
	   	"novelId":$(".novelId").val(),
	   	"authorId":booktable.book.authorId,
	   	"cover":$(".cover").val(),
	   	"introduce":$(".introduce").val(),
	   	"sentiment":$(".sentiment").val(),
	   	"collectionNumber":$(".collectionNumber").val(),
	   	"novelName":$(".bookName").val(),
			"categories":types
	   }
	   var index = layer.load(0, {shade: false}); 
	   Vue.http.post(global_url+'/admin/novel/updata/',data).then(
	   	response=>{
	   		layer.close(index);
	   		layer.closeAll("iframe");
	   		//刷新父页面
	   		parent.location.reload();
	   	},
	   	response=>{
	   		layer.close(index);
	   	})
	   console.log(types)
        return false;
    })
	
    //预览
    form.on("submit(look)",function(){
        layer.alert("此功能需要前台展示，实际开发中传入对应的必要参数进行文章内容页面访问");
        return false;
    })

    //创建一个编辑器
    var editIndex = layedit.build('news_content',{
        height : 535,
        uploadImage : {
            url : "../../json/newsImg.json"
        }
    });
	

	setTimeout(function(){
		flow.load({
				elem: '#LAY_demo1' //流加载容器
				,scrollElem: '#LAY_demo1' //滚动条所在元素，一般不用填，此处只是演示需要。,
				,isAuto:true
				,done: function(page, next){ //执行下一页的回调,,,
					data={
						"novel":{
							"id":$(".id").val()
						},
						"pageNum":page,
						"pageSize":20
					}
					if($(".id").val()!=null&&$(".id").val()!="")
					Vue.http.post(global_url+'/admin/novel/query/chapters/name',data).then(
						response=>{
							var lis = [];
							
							booktable.book=response.body.datas.book.novel
							booktable.chapterNum=response.body.datas.book.chapterNum
							
							console.log(response.body.datas.book.chapters)
							charinit()
							for(var i = 0; i < response.body.datas.book.chapters.length; i++){
								var html='<li onclick="js_method('+response.body.datas.book.chapters[i].chapterNo+')"><a href="#tips">'+response.body.datas.book.chapters[i].chapterNo +'</a></li>'
							  lis.push(html)
							}
							
							next(lis.join(''), page < response.body.datas.book.totalPages); //假设总页数为 10
						},
						response=>{
							
						}
					)

				}
			  });
	},500)

	$(".search_btn").on("click",function(){
        if($(".searchVal").val() != ''){
			js_method($(".searchVal").val())
        }else{
            layer.msg("请输入搜索的内容");
        }
    });
   //编辑按钮点击
    $(".edit_btn").on("click",function(){
		
		layer.confirm('你确定要保存章节内容吗？', {
		  btn: ['确定','取消'] //按钮
		}, function(){
			booktable.saveChapter(booktable.cid)
			layer.msg("已提交处理请求", {icon: 1})
		});

    });
	
	 //更新按钮点击
	    $(".updata_btn").on("click",function(){
			
				booktable.onlineUpdataChapter()
				layer.msg("已提交处理请求", {icon: 1})
	
	    });

// 
// 	//小说保存事件
// 	$(".save_btn").on("click",function(){
// 		var data={
// 			"id":booktable.book.id,
// 			"novelId":$(".novelId").val(),
// 			"authorId":booktable.book.authorId,
// 			"cover":$(".cover").val(),
// 			"introduce":$(".introduce").val(),
// 			"sentiment":$(".sentiment").val(),
// 			"collectionNumber":$(".collectionNumber").val(),
// 			"novelName":$(".bookName").val()
// 		}
// 		var index = layer.load(0, {shade: false}); 
// 		Vue.http.post(global_url+'/admin/novel/updata/',data).then(
// 			response=>{
// 				layer.close(index);
// 				layer.closeAll("iframe");
// 				//刷新父页面
// 				parent.location.reload();
// 			},
// 			response=>{
// 				layer.close(index);
// 			})
//     });
// 

		
		
	//删除按钮点击
    $(".delete_btn").on("click",function(){
		
		layer.confirm('你确定要保存章节内容吗？', {
		  title:"警告",
		  skin:"delete-class",
		  icon: 2,
		  btn: ['删除','取消'] //按钮
		}, function(){
			booktable.deleteChapter(booktable.cid)
			layer.msg("已提交处理请求", {icon: 1})
		}); 

    });



	//手动添加按钮点击
    $(".manual_btn").on("click",function(){
		
		layer.confirm('你确定要将可修改区域的内容添加吗？', {
		  title:"提示",
		  icon: 3,
		  btn: ['确定','取消'] //按钮
		}, function(){
			booktable.addChapter()
			layer.msg("已提交处理请求", {icon: 1})
		}); 

    });
	
	
	//程序添加按钮点击
	$(".add_btn").on("click",function(){
		layer.prompt({title: '请输入章节地址', formType: 3}, function(pass, index){
			booktable.addOnlineChapter(pass)
		  layer.close(index);
		  layer.msg('请求成功，请过会再来刷新界面', {
			  offset: 't',
			  anim: 6
			});
		});
    });
		
		
		
		//刷新表单的复选框
		setTimeout(function(){
				form.render('checkbox',"bookinfopage");

		},100);

})


function js_method(data){
	
	Vue.http.post(global_url+'/admin/chapter/query/id/'+booktable.book.id+'/'+data).then(
		response=>{
			if(response.body.datas.chapter==null){
				booktable.notice.init({
					type: "danger",
					autoClose: true,
					title: "没有当前章节",
					desktop: true,
				});
				return
			}
			
			booktable.bookName=booktable.book.novelName
			booktable.bookauthor=booktable.book.author.penName
			booktable.id=data
			booktable.charptTitle=response.body.datas.chapter.chapterName
			booktable.content=response.body.datas.chapter.chapterContent
			booktable.cnum=response.body.datas.chapter.chapterContent.length
			booktable.cid=response.body.datas.chapter.id
			charinit()
		},
		response=>{
			booktable.notice.init({
				type: "danger",
				autoClose: true,
				title: "请求失败",
				desktop: true,
			});
		}
	)
	
}
